from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session, joinedload
from typing import List, Optional
from datetime import datetime

from database import get_db
from models.user import User
from models.post import Post
from models.comment import Comment
from schemas.comment import CommentCreate, CommentResponse, CommentUpdate
from routers.auth import get_current_user

router = APIRouter()

@router.get("/posts/{post_id}/comments", response_model=List[CommentResponse])
async def get_comments(
    post_id: str,
    db: Session = Depends(get_db)
):
    """获取文章评论列表"""
    # 检查文章是否存在
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="文章不存在"
        )
    
    # 获取评论列表（只显示已审核的评论），使用joinedload预加载作者信息
    comments = db.query(Comment).options(
        joinedload(Comment.author)
    ).filter(
        Comment.post_id == post_id,
        Comment.is_approved == True,
        Comment.parent_id.is_(None)  # 只获取顶级评论
    ).order_by(Comment.created_at.desc()).all()
    
    return comments

@router.post("/posts/{post_id}/comments", response_model=CommentResponse)
async def create_comment(
    post_id: str,
    comment: CommentCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建评论"""
    # 检查文章是否存在
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="文章不存在"
        )
    
    # 创建评论
    db_comment = Comment(
        content=comment.content,
        author_id=current_user.id,
        post_id=post_id,
        parent_id=comment.parent_id
    )
    
    db.add(db_comment)
    db.commit()
    db.refresh(db_comment)
    
    # 重新查询以获取完整的作者信息
    db_comment = db.query(Comment).options(
        joinedload(Comment.author)
    ).filter(Comment.id == db_comment.id).first()
    
    return db_comment

@router.put("/comments/{comment_id}", response_model=CommentResponse)
async def update_comment(
    comment_id: int,
    comment: CommentUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新评论"""
    db_comment = db.query(Comment).filter(Comment.id == comment_id).first()
    if not db_comment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="评论不存在"
        )
    
    # 检查权限（只有作者可以编辑）
    if db_comment.author_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限编辑此评论"
        )
    
    # 更新评论内容
    db_comment.content = comment.content
    db_comment.updated_at = datetime.utcnow()
    
    db.commit()
    db.refresh(db_comment)
    
    return db_comment

@router.delete("/comments/{comment_id}")
async def delete_comment(
    comment_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除评论"""
    db_comment = db.query(Comment).filter(Comment.id == comment_id).first()
    if not db_comment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="评论不存在"
        )
    
    # 检查权限（只有作者或管理员可以删除）
    if db_comment.author_id != current_user.id and not current_user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限删除此评论"
        )
    
    db.delete(db_comment)
    db.commit()
    
    return {"message": "评论删除成功"}
